package org.jsola.hr.web;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.FormGroupFieldAddDTO;
import org.jsola.hr.dto.FormGroupFieldBatchDTO;
import org.jsola.hr.dto.FormGroupFieldUpdateDTO;
import org.jsola.hr.dto.SiteFieldAddDTO;
import org.jsola.hr.query.FormGroupFieldQuery;
import org.jsola.hr.service.IFormGroupFieldService;
import org.jsola.hr.service.IFormGroupService;
import org.jsola.hr.vo.FormGroupFieldListVO;
import org.jsola.hr.vo.FormGroupFieldVO;
import org.jsola.hr.vo.FormGroupVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import javax.validation.Valid;


/**
 * 表单字段
 *
 * @author zhr
 */
@RestController("hrFormGroupFieldController")
@RequestMapping(HrConstants.API_PATH + "/v1/formGroupFields")
public class FormGroupFieldController implements IFormGroupFieldControllerAPI {

    @Autowired
    private IFormGroupFieldService formGroupFieldService;

    @Autowired
    private IFormGroupService formGroupService;

    @Override
    @PostMapping
    public Result<FormGroupFieldVO> save(@Valid @RequestBody FormGroupFieldAddDTO formGroupFieldAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增表单字段权限校验

        return Result.success(
                formGroupFieldService.save(formGroupFieldAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody FormGroupFieldUpdateDTO formGroupFieldUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改表单字段权限校验

        //校验中文名不能重复
        String newFieldName = formGroupFieldUpdateDTO.getFieldName().trim();
        Long newFieldId = formGroupFieldUpdateDTO.getId();
        List<FormGroupVO> result = formGroupService.findBySiteId("gys", tokenUser);
        for (FormGroupVO formGroupVO : result) {
            List<FormGroupFieldVO> list = formGroupVO.getFormGroupFieldList();
            for (FormGroupFieldVO formGroupFieldVO : list) {
                String fieldName = formGroupFieldVO.getFieldName();
                Long fieldId = formGroupFieldVO.getId();
                if (newFieldName.equals(fieldName) && !newFieldId.equals(fieldId)) {
                    throw new ParamException("自定义字段已存在");
                }
            }
        }

        int count = formGroupFieldService.update(formGroupFieldUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody FormGroupFieldBatchDTO formGroupFieldBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<FormGroupFieldAddDTO> formGroupFieldAddDTOList = formGroupFieldBatchDTO.getFormGroupFieldAddDTOList();
        if (!CollectionUtils.isEmpty(formGroupFieldAddDTOList)) {
            formGroupFieldService.batchSave(formGroupFieldAddDTOList, tokenUser);
        }
        // 修改
        List<FormGroupFieldUpdateDTO> formGroupFieldUpdateDTOList = formGroupFieldBatchDTO.getFormGroupFieldUpdateDTOList();
        if (!CollectionUtils.isEmpty(formGroupFieldUpdateDTOList)) {
            formGroupFieldUpdateDTOList.parallelStream().forEach(
                    formGroupFieldUpdateDTO -> {
                        formGroupFieldService.update(formGroupFieldUpdateDTO, tokenUser);
                    }
            );
        }
        // 删除
        List<Long> deleteFormGroupFieldIdList = formGroupFieldBatchDTO.getDeleteFormGroupFieldIdList();
        if (!CollectionUtils.isEmpty(deleteFormGroupFieldIdList)) {
            formGroupFieldService.deleteByIds(tokenUser, false, deleteFormGroupFieldIdList.toArray(new Long[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{formGroupFieldId}")
    public Result<Integer> delete(@PathVariable Long formGroupFieldId,
                                  @RequestParam(required = false) Boolean check) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除表单字段权限校验

        int count = formGroupFieldService.deleteByIds(tokenUser, check, formGroupFieldId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody Long[] formGroupFieldIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除表单字段权限校验

        int count = formGroupFieldService.deleteByIds(tokenUser, false, formGroupFieldIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{formGroupFieldId}")
    public Result<FormGroupFieldVO> findById(@PathVariable Long formGroupFieldId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看表单字段权限校验

        return Result.success(
                formGroupFieldService.selectById(formGroupFieldId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<FormGroupFieldListVO>> listAll(@Valid FormGroupFieldQuery formGroupFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看表单字段权限校验

        return Result.success(
                formGroupFieldService.select(formGroupFieldQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<FormGroupFieldListVO>> page(@Valid FormGroupFieldQuery formGroupFieldQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                formGroupFieldService.selectPage(formGroupFieldQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/saveSiteField")
    public Result<FormGroupFieldVO> saveSiteField(@Valid @RequestBody SiteFieldAddDTO siteFieldAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增表单字段权限校验

        //校验中文名不能重复
        String newFieldName = siteFieldAddDTO.getFieldName().trim();
        List<FormGroupVO> result = formGroupService.findBySiteId("gys", tokenUser);
        for (FormGroupVO formGroupVO : result) {
            List<FormGroupFieldVO> list = formGroupVO.getFormGroupFieldList();
            for (FormGroupFieldVO formGroupFieldVO : list) {
                String fieldName = formGroupFieldVO.getFieldName();
                if (newFieldName.equals(fieldName)) {
                    throw new ParamException("自定义字段已存在");
                }
            }
        }

        FormGroupFieldAddDTO formGroupFieldAddDTO = siteFieldAddDTO.to(FormGroupFieldAddDTO.class);
        formGroupFieldAddDTO.setFieldSource(2);
        formGroupFieldAddDTO.setIsEdit(0);
        formGroupFieldAddDTO.setIsNecessary(false);
        formGroupFieldAddDTO.setIsOpen(true);
        formGroupFieldAddDTO.setSubjectType("site");
        formGroupFieldAddDTO.setSubjectId(tokenUser.getSiteId());
        FormGroupFieldVO formGroupFieldVO = formGroupFieldService.save(formGroupFieldAddDTO, tokenUser);
        return Result.success(formGroupFieldVO);
    }


}

